package com.dreamcode.anfeedreader.activity;

import java.net.MalformedURLException;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dreamcode.anfeedreader.collectors.FeedsDAOimpl;
import com.dreamcode.anfeedreader.collectors.ItemListAdapter;
import com.dreamcode.anfeedreader.modelClass.Feed;
import com.dreamcode.anfeedreader.utils.IOUtils;

public class NewFeedActivity extends Activity{

	private FeedsDAOimpl feedsDAO = null;
	private Button btnNew = null;
	private Button btnOk = null;
	private Button btnCancel = null;
	private int mode = 0;
	private int feedId;
	private EditText feednName = null;
	private EditText feedUrl = null;
	private IOUtils ioUtils = null;
	private Spinner groupSpinner = null;	
	private Object favIconObject = null;
	private final static int EDIT_MODE = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.newfeed);
		initView();
	}
	
	public void initView(){
		final String[] array = {"sunday", "monday", "tuesday", "wednesday"};
		feedsDAO = FeedsDAOimpl.getInstance();
		feednName = (EditText) findViewById(R.id.edit_name);
		feedUrl = (EditText) findViewById(R.id.edit_url);		
		ioUtils = new IOUtils();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			mode = bundle.getInt("mode");
		}
		if (mode == EDIT_MODE) {
			feedId = bundle.getInt("id");
			Feed feed = feedsDAO.getFeed(NewFeedActivity.this, feedId);
			if (feed != null) {
				feednName.setText(feed.getTitle());
				feedUrl.setText(feed.getUrl());
//				favUrl = (feed.getFeedIconUrl()!=null && !feed.getFeedIconUrl().equals(""))?feed.getFeedIconUrl():"";
			}
		}
		btnNew = (Button) findViewById(R.id.btn_new_group);
		btnNew.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				createGroupDialog();				
			}
		});
		
		btnOk = (Button) findViewById(R.id.btn_ok);
		btnOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if((feednName.getText().toString()!=null && !feednName.getText().toString().equals(""))
						&& (feedUrl.getText().toString()!=null && !feedUrl.getText().toString().equals(""))){
					List<Object> values = new LinkedList<Object>();
					values.add(feednName.getText().toString());
					values.add(feedUrl.getText().toString());
					if(mode == EDIT_MODE){
						if(favIconObject!=null)
							values.add(favIconObject);
					}else{						
						try {
							byte [] favIcon = ioUtils.updateFavicon(NewFeedActivity.this, ioUtils.getDefaultFavicon(feedUrl.getText().toString()).toString());
							values.add(favIcon!=null?favIcon.toString():null);
						} catch (MalformedURLException e) {
							e.printStackTrace();
						}
					}
					if (groupSpinner.getSelectedView() != null) {
					  values.add(String.valueOf((groupSpinner.getSelectedView()).getId()));
					} else {
					  values.add("0");
					}
					if (mode == EDIT_MODE) {
						values.add(String.valueOf(feedId));
						feedsDAO.updateEditedFeed(NewFeedActivity.this, values);
					} else {
						feedsDAO.insertNewFeed(NewFeedActivity.this, values);						
					}
					Toast.makeText(NewFeedActivity.this, (CharSequence)Html.fromHtml(getString(R.string.feed_entered)), Toast.LENGTH_LONG).show();
					finish();
				}else{
					Toast.makeText(NewFeedActivity.this, (CharSequence)Html.fromHtml(getString(R.string.required_allfeeds)), Toast.LENGTH_LONG).show();
				}
			}
		});
		
		btnCancel = (Button) findViewById(R.id.btn_cancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
		
		groupSpinner = (Spinner) findViewById(R.id.group_selector);		
		groupSpinner.setAdapter(new ItemListAdapter(NewFeedActivity.this, feedsDAO.getAllFeedCategories(NewFeedActivity.this)));
	}
	
	public void createGroupDialog(){
		final LinearLayout container = new LinearLayout(NewFeedActivity.this);
		container.setOrientation(LinearLayout.VERTICAL);
		final TextView textView = new TextView(NewFeedActivity.this);
		textView.setText("Group Name:");		
		final EditText editText = new EditText(NewFeedActivity.this);
		editText.setMinWidth(200);
		editText.setMaxWidth(200);
		container.addView(textView);
		container.addView(editText);		
		AlertDialog groupDialog = new AlertDialog.Builder(NewFeedActivity.this).setTitle("New Group").setView(container)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(editText.getText().toString()!=null && !editText.getText().toString().equals("")){
					feedsDAO.insertCategory(NewFeedActivity.this, editText.getText().toString());
					dialog.dismiss();	
					Toast.makeText(NewFeedActivity.this, (CharSequence)Html.fromHtml(getString(R.string.enter_newcategory)), Toast.LENGTH_LONG).show();
					initSpinner();
				}else{
					Toast.makeText(NewFeedActivity.this, (CharSequence)Html.fromHtml(getString(R.string.category_name_required)), Toast.LENGTH_LONG).show();
					createGroupDialog();
				}
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();				
			}
		}).show();
		
	}
	
	public void initSpinner(){
		groupSpinner.setAdapter(new ItemListAdapter(NewFeedActivity.this, feedsDAO.getAllFeedCategories(NewFeedActivity.this)));
	}

}
